<template>
    <!-- 新增客户弹窗 -->
    <el-dialog :model-value="props.modelValue" @update:model-value="emit('update:modelValue', $event)" title="新增客户"
        width="75%" :before-close="handleCloseDialog">
        <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px">
            <!-- 类型选择 -->
            <el-form-item label="类型">
                <el-radio-group v-model="addForm.category">
                    <el-radio label="customer">客户</el-radio>
                    <el-radio label="supplier">客户/供应商</el-radio>
                </el-radio-group>
            </el-form-item>

            <!-- 基础信息 -->
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="客户名称" prop="name">
                        <el-input v-model="addForm.name" placeholder="请输入客户名称" />
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="客户类别" prop="type">
                        <el-tree-select :data="treeSelectData" v-model="addForm.type" placeholder="请选择客户类别"
                            style="width: 100%;" clearable
                            :props="{ value: 'id', label: 'name', children: 'children' }">
                            <template #default="{ data }">
                                <span>
                                    <el-icon>
                                        <Folder v-if="data.children && data.children.length > 0" />
                                        <Document v-else />
                                    </el-icon>
                                    {{ data.name }}
                                </span>
                            </template>
                        </el-tree-select>
                    </el-form-item>
                </el-col>

            </el-row>

            <el-row :gutter="20">

                <el-col :span="12">
                    <el-form-item label="客户等级" prop="level">
                        <el-select v-model="addForm.level" placeholder="请选择客户等级" style="width: 100%;">
                            <el-option v-for="item in levelList" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="余额日期" prop="balanceDate">
                        <el-date-picker v-model="addForm.balanceDate" type="date" placeholder="选择日期" format="YYYY-MM-DD"
                            style="width: 100%;" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="期初应收款" prop="initialReceivable" :label-Width="formLabelWidth">
                        <el-input v-model="addForm.initialReceivable" placeholder="请输入期初应收款"></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="期初预收款" prop="initialAdvance" :label-Width="formLabelWidth">
                        <el-input v-model="addForm.initialAdvance" placeholder="请输入期初预收款"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="业务员" prop="salesman">
                        <el-select v-model="addForm.salesman" placeholder="请选择业务员" style="width: 100%;">
                            <el-option v-for="item in staffList" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="交货方式" prop="delivery">
                        <el-select v-model="addForm.deliveryMethod" placeholder="请选择交货方式" style="width: 100%;">
                            <el-option :value="1" label="快递物流" />
                            <el-option :value="2" label="自配" />
                            <el-option :value="3" label="其他" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="收款条件" prop="paymentTerms">
                        <el-select v-model="addForm.paymentTerms" placeholder="请选择" style="width: 100%;">
                            <el-option :value="1" label="现结" />
                            <el-option :value="2" label="货到付款" />
                            <el-option :value="3" label="分期付款" />
                            <el-option :value="4" label="先款后付" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 发票信息 -->
            <div style="margin-top: 20px; border-top: 1px solid #e4e7ed; padding-top: 15px;">
                <h3>发票信息</h3>
            </div>

            <el-row :gutter="30">
                <el-col :span="12">
                    <el-form-item label="纳税人识别号" prop="taxCode">
                        <el-input v-model="addForm.taxCode" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="开户银行" prop="bank">
                        <el-input v-model="addForm.bank" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="银行账号" prop="account">
                        <el-input v-model="addForm.account" />
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 联系人表格 -->
            <div style="margin-top: 20px; border-top: 1px solid #e4e7ed; padding-top: 15px;">
                <h3>联系人</h3>

                <div style="display: flex; align-items: center; gap: 12px;">
                    <!-- 上传附件按钮 -->
                    <el-button type="text" style="color: #409EFF;">
                        <el-icon>
                            <Upload />
                        </el-icon>
                        上传附件
                    </el-button>
                    <!-- 搜索框 -->
                    <div v-if="!customerDialogType">
                        <el-input v-model="contactSearch.keyword" placeholder="请输入联系人/手机号搜索" style="width: 240px;"
                            size="small" />
                        <el-button type="primary" size="small" @click="searchContact">查询</el-button>
                    </div>

                </div>

                <el-table :data="addForm.contacts" style="width: 100%" border height="200">

                    <el-table-column label="操作" width="100" align="center">
                        <template #default="{ $index }">
                            <el-button @click="addContactRow($index)" link size="small" icon="Plus" title="添加联系人" />

                            <el-button @click="removeContact($index)" link size="small" icon="Delete" title="删除联系人" />
                        </template>
                    </el-table-column>

                    <el-table-column prop="name" label="联系人">
                        <template #default="{ row }">
                            <el-input v-model="row.name" placeholder="姓名" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="phone" label="手机">
                        <template #default="{ row }">
                            <el-input v-model="row.phone" placeholder="手机" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="fax" label="座机">
                        <template #default="{ row }">
                            <el-input v-model="row.fax" placeholder="座机" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="email" label="QQ/微信/Email">
                        <template #default="{ row }">
                            <el-input v-model="row.email" placeholder="邮箱/QQ/微信" />
                        </template>
                    </el-table-column>

                    <el-table-column label="联系地址">
                        <template #default="{ row, $index }">
                            <div class="address-cell" @click="openAddressDialog(row, $index)">
                                <span v-if="row.address">{{ row.address }}</span>
                                <span v-else class="placeholder">点击设置地址</span>
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column label="首要联系人">
                        <template #default="{ row }">
                            <el-select v-model="row.isFirst" @change="setPrimary(row)" placeholder="请选择">
                                <el-option label="是" :value="1" />
                                <el-option label="否" :value="0" />
                            </el-select>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 备注 -->
            <el-form-item label="备注" prop="remark" style="margin-top: 20px;">
                <el-input v-model="addForm.remark" type="textarea" :rows="4" />
            </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">关闭</el-button>
                <el-button type="primary" @click="submitAddForm" :loading="saving">保存</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 地址编辑对话框 -->
    <el-dialog v-model="addressDialog.visible" title="编辑联系地址" width="420px" @close="closeAddressDialog">
        <el-form label-position="top">
            <!-- 省市区级联 -->
            <el-form-item label="省 / 市 / 区" required>
                <el-cascader v-model="addressDialog.form.region" :options="regionData" placeholder="请选择省市区"
                    style="width: 100%" size="small" clearable filterable @change="handleRegionChange" />
            </el-form-item>

            <!-- 详细地址 -->
            <el-form-item label="详细地址" required>
                <el-input v-model="addressDialog.form.detailAddress" placeholder="街道、门牌号、楼栋等" size="small"
                    @input="updateFullAddress" />
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="closeAddressDialog">取消</el-button>
            <el-button type="primary" @click="saveAddress" :loading="loading">
                确定
            </el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, computed, defineProps, defineEmits } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { regionData, codeToText } from 'element-china-area-data'
import axios from 'axios'

const saving = ref(false)
const addFormRef = ref(null)
const loading = ref(false)
const formLabelWidth = '140px'

const contactSearch = reactive({ keyword: '' })
const customerDialogType = ref(true)

const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false
    },
});

const emit = defineEmits(['update:modelValue', 'confirm']);


// 新增表单数据
const addForm = reactive({
    category: 'customer',
    // 客户信息
    code: '',
    type: '',
    level: '',
    salesman: '',
    balanceDate: null,
    initialReceivable: null,
    initialAdvance: null,
    receivableBalance: null,
    deliveryMethod: null,
    paymentTerms: null,
    remark: '',
    // 开票信息
    taxCode: '',
    bank: '',
    account: '',
    // 联系人信息
    contacts: [
        {
            name: '',
            phone: '',
            fax: '',
            email: '',
            address: '',
            isFirst: null
        }
    ]
})

// 客户类别数据
const customerTypeList = ref([])

// 获取客户类别
const getCustomerType = async () => {
    const res = await axios.get('/api/basic/customer/allCustomerTypes')
    if (res.data.code === 5200) {
        customerTypeList.value = res.data.customerTypeList
    }
}

// 构建树形数据
const treeData = computed(() => {
    const roots = []

    const map = {}

    customerTypeList.value.forEach(item => {
        map[item.id] = { ...item, children: [] }
    })

    customerTypeList.value.forEach(item => {
        if (item.parentId == null || item.parentId == '0') {
            roots.push(map[item.id])
        } else {
            const parentObj = map[item.parentId]
            if (parentObj) {
                parentObj.children.push(map[item.id])
            }
        }
    })
    return roots
})

const treeSelectData = computed(() => {
    const enabledTreeData = treeData.value
    return [
        {
            id: '0',
            name: '全部',
            children: enabledTreeData
        }
    ]
})

// 客户等级
const levelList = ref([])
const getLevelList = async () => {
    try {
        const res = await axios.get('/api/basic/customer/customerLevels')
        if (res.data.code === 5200) {
            levelList.value = res.data.customerLevels
        } else {
            ElMessage.error(res.data.message)
        }
    } catch (error) {
        console.error('加载等级列表失败:', error)
        ElMessage.error('加载等级列表失败: ' + (error.response?.data?.msg || error.message))
    }
}

// 业务员
const staffList = ref([])

const getStaffList = async () => {
    try {
        const res = await axios.get('/api/basic/enterprise/allStaff')
        if (res.data.code === 5200) {
            staffList.value = res.data.staffList
        } else {
            ElMessage.error(res.data.message)
        }
    } catch (error) {
        console.error('加载业务员列表失败:', error)
        ElMessage.error('加载业务员列表失败: ' + (error.response?.data?.msg || error.message))
    }
}

// 地址对话框状态
const addressDialog = reactive({
    visible: false,
    currentContact: null,
    currentIndex: -1,
    form: {
        region: [],
        detailAddress: '',
        fullAddress: ''
    }
})

// 表单验证规则
const addFormRules = {
    code: [{ required: true, message: '请输入客户编号', trigger: 'blur' }],
    name: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
    type: [{ required: true, message: '请选择客户类别', trigger: 'change' }],
    level: [{ required: true, message: '请选择客户等级', trigger: 'change' }]
}

// 在当前行后添加联系人
const addContactRow = (index) => {
    addForm.contacts.splice(index + 1, 0, {
        name: '',
        phone: '',
        fax: '',
        email: '',
        address: '',
        isFirst: null
    })
}

// 删除联系人
const removeContact = (index) => {
    if (addForm.contacts.length > 1) {
        addForm.contacts.splice(index, 1)
        ElMessage.success('联系人已删除')
    } else {
        ElMessage.warning('至少需要保留一个联系人')
    }
}

// 设置首要联系人
const setPrimary = (currentRow) => {
    addForm.contacts.forEach(item => {
        item.isFirst = (item === currentRow) ? 1 : 0
    })
}

// 搜索联系人
const searchContact = () => {
    console.log()
}

// 打开地址对话框（支持回显）
const openAddressDialog = (contact, index) => {
    addressDialog.currentContact = contact
    addressDialog.currentIndex = index

    if (contact.address) {
        const parsedData = parseExistingAddress(contact.address)
        addressDialog.form = {
            region: parsedData.region || [],
            detailAddress: parsedData.detailAddress || '',
            fullAddress: contact.address
        }
    } else {
        addressDialog.form = {
            region: [],
            detailAddress: '',
            fullAddress: ''
        }
    }
    addressDialog.visible = true
}

// 解析现有地址
const parseExistingAddress = (address) => {
    if (!address) return { region: [], detailAddress: '' }

    try {
        const parts = address.split(' ')
        if (parts.length >= 3) {
            const provinceName = parts[0]
            const cityName = parts[1]
            const districtName = parts[2]
            const detailAddress = parts.slice(3).join(' ') || ''

            const regionCodes = findRegionCodes(provinceName, cityName, districtName)
            return { region: regionCodes, detailAddress }
        }
        return { region: [], detailAddress: address }
    } catch (error) {
        return { region: [], detailAddress: address }
    }
}

// 查找地区代码
const findRegionCodes = (provinceName, cityName, districtName) => {
    try {
        for (const province of regionData) {
            if (codeToText[province.value] === provinceName) {
                if (province.children) {
                    for (const city of province.children) {
                        if (codeToText[city.value] === cityName) {
                            if (city.children) {
                                for (const district of city.children) {
                                    if (codeToText[district.value] === districtName) {
                                        return [province.value, city.value, district.value]
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return []
    } catch (error) {
        return []
    }
}

// 安全处理地区选择变化
const handleRegionChange = (value) => {
    try {
        addressDialog.form.region = Array.isArray(value) ? value : []
        updateFullAddress()
    } catch (error) {
        console.error('处理地区选择变化失败:', error)
        addressDialog.form.region = []
    }
}

// 安全更新完整地址
const updateFullAddress = () => {
    try {
        const { region, detailAddress } = addressDialog.form

        addressDialog.form.fullAddress = detailAddress || ''

        if (!region || region.length !== 3) {
            return
        }

        const provinceCode = region[0]
        const cityCode = region[1]
        const districtCode = region[2]

        if (!provinceCode || !cityCode || !districtCode) {
            return
        }

        const province = codeToText[provinceCode] || ''
        const city = codeToText[cityCode] || ''
        const district = codeToText[districtCode] || ''

        if (!province || !city || !district) {
            return
        }

        const regionText = `${province} ${city} ${district}`
        addressDialog.form.fullAddress = detailAddress ?
            `${regionText} ${detailAddress}`.trim() : regionText

    } catch (error) {
        console.error('生成完整地址失败:', error)
        addressDialog.form.fullAddress = addressDialog.form.detailAddress || ''
    }
}

// 保存地址
const saveAddress = async () => {
    try {
        loading.value = true

        if (!addressDialog.form.region || addressDialog.form.region.length !== 3) {
            ElMessage.error('请选择完整的省市区')
            return
        }

        if (!addressDialog.form.detailAddress?.trim()) {
            ElMessage.error('请输入详细地址')
            return
        }

        if (addressDialog.currentContact) {
            Object.assign(addressDialog.currentContact, {
                address: addressDialog.form.fullAddress.trim()
            })

            ElMessage.success('地址保存成功')
            closeAddressDialog()
        }

    } catch (error) {
        console.error('保存地址失败:', error)
        ElMessage.error('保存失败: ' + (error.message))
    } finally {
        loading.value = false
    }
}

// 关闭地址对话框
const closeAddressDialog = () => {
    addressDialog.visible = false
    resetAddressForm()
}

// 重置地址表单
const resetAddressForm = () => {
    addressDialog.form = {
        region: [],
        detailAddress: '',
        fullAddress: ''
    }
    addressDialog.currentContact = null
    addressDialog.currentIndex = -1
}

// 保存客户信息
const submitAddForm = async () => {
    // try {
    //     await addFormRef.value.validate()
    // } catch (error) {
    //     ElMessage.error('请检查表单填写是否正确')
    //     return
    // }

    // 过滤空联系人
    const validContacts = addForm.contacts.filter(contact =>
        contact.name || contact.phone || contact.fax || contact.email || contact.address
    )

    // 检查是否至少有一个有效联系人
    if (validContacts.length === 0) {
        ElMessage.warning('请至少添加一个有效的联系人信息')
        return
    }

    // 检查是否有首要联系人
    const hasPrimary = validContacts.some(contact => contact.isFirst === 1)
    if (!hasPrimary) {
        // 如果没有设置首要联系人，自动设置第一个为首要
        validContacts[0].isFirst = 1
        // ElMessage.info('已自动设置第一个联系人为首要联系人')
    }

    // 构造请求体 - 匹配后端的CustomerRequest结构
    const customerRequest = {
        customer: {
            code: addForm.code,
            name: addForm.name,
            type: addForm.type,
            level: addForm.level,
            salesman: addForm.salesman,
            balanceDate: addForm.balanceDate,
            initialReceivable: addForm.initialReceivable || 0,
            initialAdvance: addForm.initialAdvance || 0,
            receivableBalance: addForm.receivableBalance,
            taxCode: addForm.taxCode,
            bank: addForm.bank,
            account: addForm.account,
            deliveryMethod: addForm.deliveryMethod,
            paymentTerms: addForm.paymentTerms,
            remark: addForm.remark,
        },
        contactList: validContacts.map(contact => ({
            name: contact.name || '',
            phone: contact.phone || '',
            fax: contact.fax || '',
            email: contact.email || '',
            address: contact.address || '',
            isFirst: contact.isFirst === 1 ? 1 : 0
        }))
    }

    try {
        saving.value = true

        const url = '/api/basic/customer/addCustomer'

        const res = await axios.post(url, customerRequest)
        if (res.data.code === 5200) {
            ElMessage.success('客户创建成功！')
            resetAddForm()
        } else {
            ElMessage.error(res.data.message || '创建失败')
        }
    } catch (error) {
        console.error('创建客户失败:', error)
        ElMessage.error('创建失败: ' + (error.response?.data?.message || error.message))
    } finally {
        saving.value = false
    }
}

// 重置表单
const resetAddForm = () => {
    Object.assign(addForm, {
        code: '',
        name: '',
        type: '',
        level: '',
        salesman: '',
        balanceDate: null,
        initialReceivable: null,
        initialAdvance: null,
        deliveryMethod: null,
        receivableBalance: null,
        paymentTerms: null,
        remark: '',
        taxCode: '',
        bank: '',
        account: '',
        contacts: [
            {
                name: '',
                phone: '',
                fax: '',
                email: '',
                address: '',
                isFirst: 1
            }
        ]
    })

    // 重置表单验证状态
    if (addFormRef.value) {
        addFormRef.value.clearValidate()
    }
}

// 关闭前确认
const handleCloseDialog = (done) => {
    ElMessageBox.confirm('当前有未保存的内容，确定关闭吗？')
        .then(() => {
            done()
            emit('update:modelValue', false)
        })
        .catch(() => { })
}

watch(() => props.modelValue, (isOpen) => {
    if (isOpen) {
        getCustomerType()
        getLevelList()
        getStaffList()
    }
})

</script>